'use strict'

const titbit = require('titbit')
const wxkey  = require('./wxkey')
const gohttp = require('gohttp')

const app = new titbit({
    debug:true
})

//必须是32位
let token_key = '12345678123456781234567812345678'

app.get('/oauth-login', async c =>{
    
    //使用gohttp发起请求调用小程序服务器api

    let login_url = `https://api.weixin.qq.com/sns/jscode2session`
            +   `?appid=${wxkey.appid}`
            +   `&secret=${wxkey.secret}`
            +   `&js_code=${c.query.code}`
            +   `&grant_type=authorization_code`

    //获取的结果是一个对象，包括headers、status、ok、data等属性
    let result = await gohttp.get(login_url)

    // //转换成文本
    // c.res.body = result.text()

    //转换成json
    let r = result.json()

    //如果获取失败则返回500错误码
    if(r.openid === undefined){
        c.statues = 500
        return
    }

    let info = {
        openid:r.openid,
        expires:7200000,
        timestamp : Date.now(),
        random:Math.random()
    }

    let token = c.helper.aesEncrypt(JSON.stringify(info),token_key)

    c.res.body=token
})

app.get('/aes-test/:data',async c=>{
    c.res.body = c.helper.aesDecrypt(c.param.data,token_key)
})

app.run(3001)